<template>
  <div class="cart container">
    <header>
      <i class="iconfont icon-fanhui" @click="$router.back()"></i>
      <span>购物车</span>
    </header>
    <div v-if="cartList.length !== 0">
      <div class="main" v-for="Object in cartList" :key="Object.id">
        <van-swipe-cell>
          <div class="my-goods-item">
            <div class="left">
              <div class="custom-control custom-checkbox">
                <van-checkbox
                  class="custom-control-input"
                  :id="Object.id"
                  v-model="Object.state"
                />
                <label class="custom-control-label" :for="Object.id">
                  <img :src="Object.imgUrl" alt="" />
                </label>
              </div>
            </div>
            <div class="right">
              <div class="top">{{ Object.name }}</div>
              <div class="bottom">
                <span class="price">¥ {{ Object.price }}</span>
                <span class="counter">
                  <div class="my-counter">
                    <button
                      type="button"
                      class="btn btn-light"
                      :disabled="Object.num === 1"
                      @click="Object.num > 1 && Object.num--"
                    >
                      -
                    </button>
                    <input
                      type="number"
                      class="form-control inp"
                      v-model.number="Object.num"
                    />
                    <button
                      type="button"
                      class="btn btn-light"
                      @click="Object.num++"
                    >
                      +
                    </button>
                  </div>
                </span>
              </div>
            </div>
          </div>
          <template #right>
            <van-button
              square
              text="删除"
              type="danger"
              class="delete-button"
              @click="deleteShop(Object.id)"
            />
          </template>
        </van-swipe-cell>
      </div>

      <!-- 底部 -->
      <div class="my-footer">
        <!-- 全选 -->
        <div class="custom-control custom-checkbox">
          <input
            type="checkbox"
            class="custom-control-input"
            id="footerCheck"
            v-model="isAll"
          />
          <label class="custom-control-label" for="footerCheck">全选</label>
        </div>
        <!-- 合计 -->
        <div>
          <span class="heji">合计:</span>
          <span class="price">¥ {{ allPrice.toFixed(2) }}</span>
        </div>
        <!-- 按钮 -->
        <button
          type="button"
          class="footer-btn btn btn-primary"
          @click="goOrder()"
        >
          结算 ( {{ allCount }} )
        </button>
      </div>
    </div>

    <section v-else class="section">
      <van-icon class="shopping-cart-o" name="shopping-cart-o" />
      <p>购物车还是空的</p>
      <p>赶紧买东西犒劳下自己</p>
      <div>
        <router-link to="/list">去逛逛吧</router-link>
      </div>
    </section>
  </div>
</template>

<script>
import http from "@/common/api/request.js";
import { mapState, mapGetters, mapMutations, mapActions } from "vuex";
export default {
  data() {
    return {
      cartList: [],
    };
  },

  created() {
    this.getCartList();
  },

  computed: {
    // 全选
    isAll: {
      set(val) {
        // val就是关联表单的值(true/false)
        this.cartList.forEach((obj) => (obj.state = val));
      },
      get() {
        // 查找小选框关联的属性有没有不符合勾选的条件
        // 直接原地false
        return this.cartList.every((obj) => obj.state === true);
      },
    },
    // 结算
    allCount() {
      return this.cartList.reduce((sum, obj) => {
        if (obj.state === true) {
          sum += +obj.num;
        }
        return sum;
      }, 0);
    },

    // 合计
    allPrice() {
      return this.cartList.reduce((sum, obj) => {
        if (obj.state) {
          sum += obj.num * obj.price;
        }
        return sum;
      }, 0);
    },
  },

  methods: {
    ...mapMutations(["initOrder"]),
    // 获取购物车数据
    async getCartList() {
      let res = await http.$axios({
        url: "http://127.0.0.1:3008/goods/goodscartlist",
      });
      this.cartList = res;
    },

    // 删除
    deleteShop(e) {
      this.$http
        .get("http://127.0.0.1:3008/goods/deletecart/" + e)
        .then((res) => {
          this.getCartList();
        });

      this.getCartList();
    },

    //去结算
    goOrder() {
      let newList = [];
      this.cartList.forEach((v) => {
        if (v.state) {
          newList.push(v);
        }
      });
      if (!newList.length) {
        return this.$toast({
          message: "请选择下单的商品",
          forbidClick: true,
          duration: 1000,
        });
      }

      //生成一个订单

      http
        .$axios({
          url: "http://127.0.0.1:3008/goods/addOrder",
          method: "post",
          // 问题1：后台获取不到前端发送的数据
          /*
           解决：
           axios默认是 json 格式提交,确认后台是否做了对应的支持;若是只能接受传统的表单序列化,
           就需要自己写一个转义的方法...当然还有一个更加省事的方案,装一个小模块qs.
           安装：
           npm install qs -S
           序列化
           data = qs.stringify(data);
          */
          headers: {
            "Content-Type": "application/x-www-form-urlencoded",
          },
          data: newList,
        })
        .then((res) => {
          this.initOrder(res.data);
          this.$router.push({
            path: "/order",
            query: {
              detail: newList,
              orderId: JSON.stringify(res.data[0].orderId),
            },
          });
        });
    },
  },

  watch: {
    obj: {
      deep: true,
      handler() {
        // 拿到商品数量, 判断小于1, 强制修改成1
        if (this.cartList.num < 1) {
          this.cartList.num = 1;
        }
      },
    },
  },
};
</script>

<style scoped lang="scss">
.container {
  width: 110%;
  margin-left: -16px;
  background-color: #f3f3f3;
  header {
    display: flex;
    align-items: center;
    height: 1.173333rem;
    color: #fff;
    background-color: #b0352f;
    i {
      padding: 0 0.4rem;
      font-size: 0.586666rem;
    }
    span {
      padding: 0 3.4rem;
      font-size: 0.426666rem;
    }
  }

  .main {
    padding-top: 22px;
    background-color: #fff;

    .delete-button {
      height: 100%;
      margin-right: 5px;
    }
    .my-goods-item {
      display: flex;
      padding: 24px;
      border-bottom: 1px solid #ccc;

      .custom-control-input {
        margin-left: 3px;
        margin-top: 7px;
      }

      .left {
        img {
          width: 85px;
          height: 116px;
          margin-right: 8px;
          border-radius: 10px;
          margin-left: 47px;
          margin-top: -29px;
        }
        .custom-control-label::before,
        .custom-control-label::after {
          top: 50px;
        }
      }
      .right {
        flex: 1;
        display: flex;
        flex-direction: column;
        justify-content: space-between;
        .top {
          font-size: 13px;
          font-weight: 500;
          margin-left: 13px;
        }
        .bottom {
          display: flex;
          justify-content: space-between;
          padding: 5px 0;
          align-items: center;
          .price {
            color: #fd3f31;
            font-weight: bold;
            font-size: 14px;
            margin-left: 13px;
          }

          .counter {
            .my-counter {
              display: flex;
              margin-right: 16px;
              .inp {
                width: 49px;
                text-align: center;
                margin: 0px 2px;
              }
              .btn,
              .inp {
                transform: scale(0.5);
              }
            }
          }
        }
      }
    }
  }

  .my-footer {
    position: fixed;
    z-index: 2;
    bottom: 0;
    width: 100%;
    height: 50px;
    border-top: 1px solid #ccc;
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 0 10px;
    background: #fff;

    input {
      margin-left: 15px;
    }
    label {
      display: inline-block;
      max-width: 100%;
      font-weight: 500;
      font-size: 19px;
      margin-left: 6px;
    }
    .heji {
      font-size: large;
      margin-left: 50px;
    }
    .price {
      color: #fd3f31;
      font-weight: bold;
      font-size: 15px;
    }
    .footer-btn {
      min-width: 80px;
      height: 30px;
      line-height: 30px;
      border-radius: 25px;
      padding: 0;
      margin-top: 9px;
      font-size: 13px;
    }

    button {
      color: #fff;
      background-color: #1989fa;
      border-color: #1989fa;
    }
  }

  .section {
    background-image: url(../../public/images/背景2.jpg);
    margin-top: 2px;
    margin-left: -4px;
    .shopping-cart-o {
      margin-left: 132px;
      margin-top: 80px;
      color: #bebebe;
      font-size: 125px;
    }
    p {
      margin-top: 23px;
      font-size: 15px;
      margin-left: 3px;
      text-align: -webkit-center;
      color: #7f7f7f;
    }
    div {
      margin-top: 70px;
      a {
        color: #5b5b5b;
        margin-left: 153px;
        font-size: 26px;
      }
    }
  }
}
</style>
